import {ReactNode} from "react";
import {useLocation, useNavigate, Location} from "react-router-dom";
import LoadingPage from "@/views/TipPage/LoadingPage";
import {whiteRoutes} from "@/router";
import useBaseStore, {BaseStoreState} from "@/store/modules/base";
import useAuthStore from "@/store/modules/auth";
import {message} from "antd";
import NProgress from 'nprogress'
import "nprogress/nprogress.css";

/**
 * 处理过程参数接口
 */
interface HandlerProps {
    location: Location;
}

/**
 * 处理认证
 */
async function handleAuth() {
    const {token} = useAuthStore.getState()
    const {auth} = useAuthStore.getState()
    if (!token) {
        throw new Error("Certification has expired")
    }
    await auth()
}

/**
 * 处理单点登录
 * @param location
 */
async function handleSSO({location}: HandlerProps) {
    const {search, hash} = location
    console.log(search, hash)
}

function isWhiteList(pathname: string): boolean {
    return whiteRoutes.includes(pathname)
}

/**
 * 路由守卫
 * @param props
 * @constructor
 */

export function Guarder(props: { children: ReactNode }) {
    const {isAuth, setIsAuth} = useBaseStore((state: BaseStoreState) => state);
    const location = useLocation();
    const navigate = useNavigate();
    if (isWhiteList(location.pathname) || isAuth) return props.children;
    const handlerProps: HandlerProps = {location};

    (async () => {
        try {
            NProgress.start();
            await handleSSO(handlerProps)
            await handleAuth()
            setIsAuth(true); // 认证完成
        } catch (error: Error | unknown) {
            if (error instanceof Error) {
                message.error(error.message)
            }
            console.error(error)
            navigate("/login?" + 'fromPath=' + location.pathname);
        } finally {
            NProgress.done();
        }
    })()
    // 没权限才会走到这里
    return <LoadingPage/>
}